<script setup lang="ts">
import { uploadAPI } from '@/apis/common';
import { createRentAPI, delEnterpriseAPI, deletRentAPI, getBuildingListAPI, getEnterpriseListAPI, getRentListAPI, outRentAPI } from '@/apis/enterprise';
import { type EnterpriseListParams,type Enterprise, type RentParams, type RentBuilding, type Datum } from '@/types/enterprise';
import { ElMessage, ElMessageBox, type FormRules, type UploadRequestOptions } from 'element-plus';
import { ref, watch } from 'vue';

//独立写一个带企业合同信息的类型
interface EnterpriseWithRent extends Enterprise {
  rentlist: Datum[];
}

const params=ref<EnterpriseListParams>({
  page:1,
  pageSize:10,
  name:''//企业名称
})
//可租赁楼宇列表
const buildingList=ref<RentBuilding[]>([])
//合同表单
const rentForm=ref<RentParams>({
  buildingId:undefined,//楼宇id
  startTime:'',//租约开始日期
  endTime:'',//租约结束日期
  contractUrl:'',//合同url
  contractId:undefined,//合同id
  type:0,//合同类型
  enterpriseId:undefined,//企业id
})
//合同rules
const rentRules = ref<FormRules<RentParams>>({
  buildingId: [
    { required: true, message: '请选择楼宇', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择租赁日期', trigger: 'blur' }
  ],
  contractId: [
    { required: true, message: '请上传合同文件' }
  ]
}) 
//企业列表
const list = ref<EnterpriseWithRent[]>([])
const total =ref(0)
const getList=async()=>{
  const res=await getEnterpriseListAPI(params.value)
  // console.log('res企业列表',res);
  list.value=res.data.rows.map(item=>({
    ...item,
    rentlist:[]
  }))
  total.value=res.data.total
}
getList()
const onSearch=() => {
params.value.page=1
getList()
}
//删除企业
const delExterprise=(id:string)=>{
  ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async() => {
    // 删除企业
    await delEnterpriseAPI(id)
    ElMessage.success('删除成功')
    getList()
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

//合同
const rentDialogVisible=ref(false)

const addRent= async(id:number)=>{
  rentDialogVisible.value=true
  const res=await getBuildingListAPI()
  buildingList.value=res.data
  //保存企业id。用于添加合同
  rentForm.value.enterpriseId=id
}
//点击添加提交合同
const addRentConfirm=async()=>{
  try{
    //校验表单
    await addForm.value?.validate()
    // 提交合同
    await createRentAPI(rentForm.value)
    ElMessage.success('添加合同成功')
    closerent()
  }catch(error){
    console.log('提交合同错误',error);
    
  }
}
const closerent=()=>{
  rentDialogVisible.value=false
  if (rentForm.value) {
    addForm.value.resetFields();
    timeArr.value=[]
  }
}
const removeupload=()=>{
  rentForm.value.contractUrl=''
  rentForm.value.contractId=undefined
  addForm.value?.validateField('contractId')
}
//上传合同
const addForm=ref()
const onUploadRequest =async (options:UploadRequestOptions) => {
  console.log('options',options);
  //1,准备ForData对象
  const fd =new FormData()
  //2,加入字段
  fd.append('file',options.file)
  fd.append('type','businessLicense')
  //3,调用接口上传文件
  const res = await uploadAPI(fd)
  console.log('res上传',res.data.url);
  //4,返回addform,触发校验
  rentForm.value.contractUrl=res.data.url
  rentForm.value.contractId=res.data.id
  addForm.value.validateField('contractId')
  return res.data
}

//日期禁用
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 1000*3600*24
}
//时间选择器，监听时间变化
const timeArr=ref<string[]>([])
watch(timeArr,(val)=>{
  if(val){
  rentForm.value.startTime=val[0]
  rentForm.value.endTime=val[1]
  }else{
    rentForm.value.startTime=''
    rentForm.value.endTime=''
  }
},{deep:true})
// 展开行时触发,将数据填充到展开页
const onExpandChange = async(row: EnterpriseWithRent) => {
  const res=await getRentListAPI(row.id)
  console.log('当前行被展开', res);
  row.rentlist=res.data
  console.log('11',row.rentlist);
  
}
//退租合同
const outRent = async(row: Datum) => {
  ElMessageBox.confirm('确定要退租吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  .then(async() => {
    const res=await outRentAPI(row.id)
    row.status = 3
    console.log('退租合同', res);
      ElMessage({
        type: 'success',
        message: '退租成功',
      })
  })
  
}
// 删除合同（合同Row, 企业Row） enterPriseRow: EnterpriseWithRent
const deleteRent = async (rentRow: Datum,row:EnterpriseWithRent) => {
  ElMessageBox.confirm('是否确认删除当前合同?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 发送请求，更新后端合同状态(后端)
    await deletRentAPI(rentRow.id)
    // 删除过滤掉合同（前端）
    // enterPriseRow.rentList = enterPriseRow.rentList.filter(item => item.id !== rentRow.id)
    await getRentListAPI(row.id)
    // 轻提示
    ElMessage.success('删除成功')
  }).catch(() => {
    // 点击取消，什么也不做
  })
}
</script>

<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input v-model="params.name" clearable @clear="onSearch" placeholder="请输入内容" class="search-main" />
      <el-button @click="onSearch" type="primary">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/exterpriseAdd')">添加企业</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="list" @expand-change="onExpandChange" row-key="id"> 
        <!-- 新增：展开部分 -->
        <el-table-column type="expand">
          <template v-slot="{row: Enterpriserow}">
            <el-table :data="Enterpriserow.rentlist">
              <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
              <el-table-column label="租赁起始时间" prop="startTime" />
              <el-table-column label="合同状态" prop="status"  >
                <template v-slot="{row}">
                  <el-tag v-if="row.status === 0" type="warning">待生效</el-tag>
                  <el-tag v-if="row.status === 1" type="success">生效中</el-tag>
                  <el-tag v-if="row.status === 2" type="info">已到期</el-tag>
                  <el-tag v-if="row.status === 3" type="danger">已退租</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="{row: rentrow}">
                  <el-button size="small" type="primary" link>续租</el-button>
                  <el-button :disabled="rentrow.status === 3" size="small" type="primary" link @click="outRent(rentrow)">退租</el-button>
                  <el-button :disabled="!(rentrow.status === 3)" size="small" type="primary" link @click="deleteRent(rentrow,Enterpriserow)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="120" />
        <el-table-column prop="name" label="企业名称" width="320" />
        <el-table-column prop="contact" label="联系人" />
        <el-table-column prop="contactNumber" label="联系电话" />
        <el-table-column prop="operation" label="操作">
          <template v-slot="{row}">
            <el-button size="small" type="primary" link @click="addRent(row.id)">添加合同</el-button>
            <el-button @click="$router.push(`/exterpriseDetail/${ row.id }`)">查看</el-button>
            <!-- <el-button size="small" type="primary" link>查看</el-button> -->
            <el-button size="small" type="primary" link @click="$router.push(`/exterpriseAdd/${row.id}`)">编辑</el-button>
            <el-button size="small" type="primary" link @click="delExterprise(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination 
      :total="total" 
      layout="total, prev, pager, next"
      :page-sizes="[2,5,10,20]"
      v-model:page-size="params.pageSize"
      v-model:current-page="params.page"
      @change="getList"
 />
    </div>
  <!-- //添加合同 -->
  <el-dialog
      v-model="rentDialogVisible"
      title="添加合同"
      width="500"
      @close="closerent"
    >
    <el-form ref="addForm" :model="rentForm" :rules="rentRules" label-position="top">
    <el-form-item label="租赁楼宇" prop="buildingId" >
      <el-select v-model="rentForm.buildingId" placeholder="请选择" clearable>
        <el-option v-for="item in buildingList" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
    </el-form-item>
    <el-form-item label="租赁起止日期" prop="endTime">
      <el-date-picker 
      v-model="timeArr" 
      type="daterange" 
      range-separator="至" 
      start-placeholder="开始日期"
      end-placeholder="结束日期" 
      value-format="YYYY-MM-DD"
      :disabled-date="disabledDate" />
    </el-form-item>
    <el-form-item label="租赁合同" prop="contractId">
      <el-upload accept=".doc, .pdf" :http-request="onUploadRequest" @remove="removeupload">
        <el-button size="small" type="primary" plain>上传合同文件</el-button>
        <template #tip>
          <div class="el-upload__tip">支持扩展名：.doc .pdf, 文件大小不超过5M</div>
        </template>
      </el-upload>
    </el-form-item>
    {{ timeArr }}
    {{ rentForm }}
  </el-form>
  <template #footer>
      <div class="dialog-footer">
        <el-button @click="closerent">取消</el-button>
        <el-button type="primary" @click="addRentConfirm">
          确认提交
        </el-button>
      </div>
    </template>
  </el-dialog>
  </div>
  
</template>

<style lang="scss" scoped>
.building-container {
  padding: 20px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>